package com.wing.inventory.service;

import com.alibaba.fastjson.JSON;
import com.google.gson.Gson;
import com.wing.auth.service.AuthService;
import com.wing.inventory.entity.request.InventoryClassRequest;
import com.wing.inventory.entity.response.CurrentStockResponse;
import com.wing.inventory.entity.response.InventoryClassResponse;
import com.wing.inventory.entity.response.InventoryResponse;
import com.wing.inventory.entity.response.InventoryUnitResponse;
import com.wing.redis.utils.redis.RedisHelperImpl;
import com.wing.set.entity.ChanjetSet;
import com.wing.set.service.ChanjetSetService;
import com.wing.util.ConstantsUtil;
import com.wing.util.HttpsUtils;
import com.wing.warehouse.entity.response.WarehouseQueryResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;

/**
 * 仓库管理
 */
@Service
@Slf4j
public class InventoryServiceImpl implements InventoryService {

    @Resource
    RedisHelperImpl redisHelper;

    @Resource
    AuthService authService;

    @Resource
    ChanjetSetService chanjetSetService;

    @Override
    public String inventoryClassCreate(InventoryClassRequest inventoryClassRequest) {
        ChanjetSet chanjetSet = chanjetSetService.getById(1L);

        Map<String, String> headers = new HashMap<>();
        headers.put("appKey", chanjetSet.getAppKey());
        headers.put("appSecret", chanjetSet.getAppSecret());

        if(redisHelper.getValue("chanjetToken") == null){
            authService.getToken();
        }
        headers.put("openToken", redisHelper.getValue("chanjetToken").toString());
        Map<String, Object> param = new HashMap<>();
        param.put("dto", inventoryClassRequest);
        String result = HttpsUtils.httpsPostByJson(ConstantsUtil.INVENTORY_CLASS_CREATE, headers, JSON.toJSONString(param));
        System.out.println("存货分类创建返回信息：" + result);
        return result;
    }

    @Override
    public List<InventoryClassResponse> inventoryClassQuery() {
        ChanjetSet chanjetSet = chanjetSetService.getById(1L);

        Map<String, String> headers = new HashMap<>();
        headers.put("appKey", chanjetSet.getAppKey());
        headers.put("appSecret", chanjetSet.getAppSecret());
        if(redisHelper.getValue("chanjetToken") == null){
            authService.getToken();
        }
        headers.put("openToken", redisHelper.getValue("chanjetToken").toString());
        Map<String, Object> queryParam = new HashMap<>();
        queryParam.put("SelectFields", "id,code,name,isendnode,parent.id,parent.code,parent.name,parent,ts,createdtime,madedate");
        Map<String, Object> param = new HashMap<>();
        param.put("param", queryParam);

        String result = HttpsUtils.httpsPostByJson(ConstantsUtil.INVENTORY_CLASS_QUERY, headers, JSON.toJSONString(param));
        Gson gson = new Gson();
        List<InventoryClassResponse> list = Arrays.asList(gson.fromJson(result, InventoryClassResponse[].class));

        return list;
    }

    @Override
    public List<InventoryUnitResponse> inventoryUnitQuery(String code) {
        ChanjetSet chanjetSet = chanjetSetService.getById(1L);

        Map<String, String> headers = new HashMap<>();
        headers.put("appKey", chanjetSet.getAppKey());
        headers.put("appSecret", chanjetSet.getAppSecret());
        if(redisHelper.getValue("chanjetToken") == null){
            authService.getToken();
        }
        headers.put("openToken", redisHelper.getValue("chanjetToken").toString());

        Map<String, Object> queryParam = new HashMap<>();
        queryParam.put("Code", code);
        Map<String, Object> param = new HashMap<>();
        param.put("param", queryParam);

        String result = HttpsUtils.httpsPostByJson(ConstantsUtil.INVENTORY_UNIT_QUERY, headers, JSON.toJSONString(param));
        System.out.println("存货计量单位返回信息：" + result);
        Gson gson = new Gson();
        List<InventoryUnitResponse> list = Arrays.asList(gson.fromJson(result, InventoryUnitResponse[].class));
        return list;
    }

    @Override
    public List<InventoryResponse> inventoryQuery() {
        List<InventoryResponse> list  = new ArrayList<>();
        return inventoryPageQuery(list, redisHelper.getValue("inventory_sync_last_ts") == null ? null :redisHelper.getValue("inventory_sync_last_ts").toString());
//        return inventoryPageQuery(list, null);
    }

    @Override
    public List<CurrentStockResponse> currentStockQuery() {
        ChanjetSet chanjetSet = chanjetSetService.getById(1L);

        Map<String, String> headers = new HashMap<>();
        headers.put("appKey", chanjetSet.getAppKey());
        headers.put("appSecret", chanjetSet.getAppSecret());
        if(redisHelper.getValue("chanjetToken") == null){
            authService.getToken();
        }
        headers.put("openToken", redisHelper.getValue("chanjetToken").toString());

        Map<String, Object> queryParam = new HashMap<>();
//        queryParam.put("PageSize", 100);
//        queryParam.put("ReBarcode", true);

        Map<String, Object> param = new HashMap<>();
        param.put("param", queryParam);
        String result = HttpsUtils.httpsPostByJson(ConstantsUtil.CURRENT_STOCK_QUERY, headers, JSON.toJSONString(param));
        System.out.println("现存量信息：" + result);
        Gson gson = new Gson();
        List<CurrentStockResponse> list = Arrays.asList(gson.fromJson(result, CurrentStockResponse[].class));
        return list;
    }

    /**
     * 分页查询
     *
     * @param ts 时间戳
     * @return
     */
    public List<InventoryResponse> inventoryPageQuery(List<InventoryResponse> inventoryList, String ts) {
        ChanjetSet chanjetSet = chanjetSetService.getById(1L);

        Map<String, String> headers = new HashMap<>();
        headers.put("appKey", chanjetSet.getAppKey());
        headers.put("appSecret", chanjetSet.getAppSecret());
        if(redisHelper.getValue("chanjetToken") == null){
            authService.getToken();
        }
        headers.put("openToken", redisHelper.getValue("chanjetToken").toString());

        Map<String, Object> queryParam = new HashMap<>();
        if (StringUtils.isNotBlank(ts)) {
            queryParam.put("Ts", ts);
        }
        queryParam.put("PageSize", 1000);
        queryParam.put("SelectFields", "ID,Code,Name,Shorthand,Specification,DefaultBarCode,Disabled,InventoryClass.Code,InventoryClass.Name,Unit.Code,Unit.Name,BaseUnitCode,BaseUnitName,ProductInfo.ID,ProductInfo.Code,ProductInfo.Name,Warehouse.ID,Warehouse.Code,Warehouse.Name,UnitByPurchase.Code,UnitByPurchase.Name,UnitBySale.Code,UnitBySale.Name,UnitByStock.Code,UnitByStock.Name,UnitByRetail.Code,UnitByRetail.Name,UnitByManufacture.Code,UnitByManufacture.Name,InvSCost,LatestCost,AvagCost,RetailPriceNew,Ts");

        Map<String, Object> param = new HashMap<>();
        param.put("param", queryParam);
        String result = HttpsUtils.httpsPostByJson(ConstantsUtil.INVENTORY_QUERY, headers, JSON.toJSONString(param));
        System.out.println("存货信息：" + result);
        Gson gson = new Gson();
        List<InventoryResponse> list = Arrays.asList(gson.fromJson(result, InventoryResponse[].class));
        if (!list.isEmpty() && list.size() > 0) {
            inventoryList.addAll(list);
            String tsDate = list.get(list.size() - 1).getTs();
            inventoryPageQuery(inventoryList, tsDate);
        }else{
            //token写入redis缓存
            redisHelper.valuePut("inventory_sync_last_ts", ts);
        }
        return inventoryList;
    }

}
